//解决锁问题 3条path
#include <rclcpp/rclcpp.hpp>
#include <moveit/move_group_interface/move_group_interface.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <geometry_msgs/msg/twist_stamped.hpp>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.hpp>
#include <atomic>
#include <thread>
#include <chrono> // 添加 chrono 头文件
#include <rclcpp/executors/multi_threaded_executor.hpp>
#include <std_msgs/msg/int32.hpp> // 添加 Int32 消息头文件

class CombinedNode : public rclcpp::Node {
public:
    CombinedNode() : Node("combined_node"), force_sign(true), closest_index(0), is_executing_(false) { // 初始化 is_executing_
        // 初始化力数据订阅
        force_sub_ = this->create_subscription<geometry_msgs::msg::TwistStamped>(
            "/force_data", 10,
            std::bind(&CombinedNode::force_callback, this, std::placeholders::_1));

        // 初始化 result2_topic 订阅者
        result_sub_ = this->create_subscription<std_msgs::msg::Int32>(
            "result2_topic", 10,
            std::bind(&CombinedNode::result_callback, this, std::placeholders::_1));

        // 初始化MoveGroupInterface
        move_group_ = std::make_shared<moveit::planning_interface::MoveGroupInterface>(
            std::shared_ptr<rclcpp::Node>(this),  // 显式创建shared_ptr
            "zc4");
        
        RCLCPP_INFO(get_logger(), "节点初始化完成");
    }

    void start_execution(int path_index) {
        // 检查是否已在执行
        if (is_executing_.exchange(true)) { // 原子地检查并设置为 true
            RCLCPP_WARN(get_logger(), "路径执行已在进行中，忽略新的请求");
            return; // 如果已在执行，则直接返回
        }

        RCLCPP_INFO(get_logger(), "开始执行路径 %d", path_index);
        std::thread([this, path_index]() {
            try {
                switch (path_index) {
                    // case 1:
                    //     executeCartesianPath1();
                    //     break;
                    // case 2:
                    //     executeCartesianPath2();
                    //     break;
                    case 3:
                        executeCartesianPath3();
                        break;
                    // default:
                    //     RCLCPP_ERROR(get_logger(), "无效的路径索引: %d", path_index);
                    //     break;
                }
                RCLCPP_INFO(get_logger(), "路径 %d 执行完成，开始等待 3 秒...", path_index);
                std::this_thread::sleep_for(std::chrono::seconds(3)); // 等待3秒
                RCLCPP_INFO(get_logger(), "等待结束");
            } catch (const std::exception& e) {
                RCLCPP_ERROR(get_logger(), "路径执行线程中发生异常: %s", e.what());
            } catch (...) {
                RCLCPP_ERROR(get_logger(), "路径执行线程中发生未知异常");
            }
            is_executing_ = false; // 执行完毕（包括延迟）后，重置标志
        }).detach();
    }

private:
    std::shared_ptr<moveit::planning_interface::MoveGroupInterface> move_group_;
    rclcpp::Subscription<geometry_msgs::msg::TwistStamped>::SharedPtr force_sub_;
    rclcpp::Subscription<std_msgs::msg::Int32>::SharedPtr result_sub_; // 添加订阅者成员变量
    std::atomic<bool> force_sign;
    std::atomic<size_t> closest_index;
    std::atomic<bool> is_executing_; // 添加执行状态标志

    void force_callback(const geometry_msgs::msg::TwistStamped::SharedPtr msg) {
        if (std::abs(msg->twist.linear.z) >= 5.0) {
            force_sign = false;
        } else {
            force_sign = true;
        }
    }

    // 添加 result2_topic 的回调函数
    void result_callback(const std_msgs::msg::Int32::SharedPtr msg) {
        // RCLCPP_INFO(get_logger(), "收到来自 result2_topic 的消息: %d", msg->data);
        if (msg->data == 1) {
            RCLCPP_INFO(get_logger(), "result2_topic 值为 1，尝试执行路径 3");
            start_execution(3); // 尝试调用 start_execution(3)
        }
    }

    bool returnToMiddle() {
        move_group_->setNamedTarget("middle");
        moveit::planning_interface::MoveGroupInterface::Plan home_plan;
        bool success = (move_group_->plan(home_plan) == moveit::core::MoveItErrorCode::SUCCESS);
        if (success) {
            move_group_->execute(home_plan);
            RCLCPP_INFO(get_logger(), "回到middle位置");
            return true;
        }
        RCLCPP_ERROR(get_logger(), "回到middle位置失败");
        return false;
    }

    bool continueCartesianPath(const std::vector<geometry_msgs::msg::Pose>& original_waypoints) {
        geometry_msgs::msg::Pose current_pose = move_group_->getCurrentPose().pose;
        std::vector<geometry_msgs::msg::Pose> remaining_waypoints;
        double min_distance = std::numeric_limits<double>::max();

        for (size_t i = 0; i < original_waypoints.size(); ++i) {
            double dx = current_pose.position.x - original_waypoints[i].position.x;
            double dy = current_pose.position.y - original_waypoints[i].position.y;
            double dz = current_pose.position.z - original_waypoints[i].position.z;
            double distance = std::sqrt(dx*dx + dy*dy + dz*dz);
            if (distance < min_distance) {
                min_distance = distance;
                closest_index = i;
            }
        }

        for (size_t i = closest_index + 1; i < original_waypoints.size(); ++i) {
            remaining_waypoints.push_back(original_waypoints[i]);
        }

        if (remaining_waypoints.empty()) return false;

        move_group_->setStartStateToCurrentState();
        moveit::planning_interface::MoveGroupInterface::Plan new_plan;
        double fraction = move_group_->computeCartesianPath(remaining_waypoints, 0.01, 0.0, new_plan.trajectory_);
        
        if (fraction >= 0.9) {
            move_group_->asyncExecute(new_plan);
            return true;
        }
        return false;
    }

    void executeCartesianPath3() {
        if (!returnToMiddle()) return;
        /* #region  */
        std::vector<geometry_msgs::msg::Pose> waypoints;
        // 目标点1 -14/-45/90/-45/0
        geometry_msgs::msg::Pose pose1;
        pose1.position.x = 0.1038794732882471;
        pose1.position.y = -0.055993214192435026;
        pose1.position.z = 0.2876041751758597;
        pose1.orientation.x = 7.895216365982998e-06;
        pose1.orientation.y = 4.925607556231088e-05;
        pose1.orientation.z = -0.12184804269604492;
        pose1.orientation.w = 0.9925487655539387;
        waypoints.push_back(pose1);

        // 目标点2 -28/-45/90/-45/0
        geometry_msgs::msg::Pose pose2;
        pose2.position.x = 0.08367758643029065;
        pose2.position.y = -0.1086808498137246;
        pose2.position.z = 0.2875887574546225;
        pose2.orientation.x = 1.927121538709558e-05;
        pose2.orientation.y = 6.971049619118313e-05;
        pose2.orientation.z = -0.24189446329796155;
        pose2.orientation.w = 0.97030256280959;
        waypoints.push_back(pose2);

        // 目标点3 -28/-50/80/15/0
        geometry_msgs::msg::Pose pose3;
        pose3.position.x = -0.024548290170542997;
        pose3.position.y = -0.051114431259759716;
        pose3.position.z = 0.14426120700169354;
        pose3.orientation.x = 0.09259218221194593;
        pose3.orientation.y = 0.37132642847766817;
        pose3.orientation.z = -0.223401705139517;
        pose3.orientation.w = 0.8964569423279657;
        waypoints.push_back(pose3);

        // 目标点4 -28/-70/120/-12/0
        geometry_msgs::msg::Pose pose4;
        pose4.position.x = 0.0059175229032937815;
        pose4.position.y = -0.06733821725529181;
        pose4.position.z = 0.08516913944763507;
        pose4.orientation.x = 0.07877489671301727;
        pose4.orientation.y = 0.3158618841182072;
        pose4.orientation.z = -0.2287160122165187;
        pose4.orientation.w = 0.9174501466373653;
        waypoints.push_back(pose4);

        // 目标点5 -28/-65/121/-17/0
        geometry_msgs::msg::Pose pose5;
        pose5.position.x = 0.014856622895562388;
        pose5.position.y = -0.0721048590648025;
        pose5.position.z = 0.06944823076037311;
        pose5.orientation.x = 0.08474302001326812;
        pose5.orientation.y = 0.3397336582584099;
        pose5.orientation.z = -0.22661422321503966;
        pose5.orientation.w = 0.908870538548826;
        waypoints.push_back(pose5);

        // 目标点6 -28/-68/128/-27/0
        geometry_msgs::msg::Pose pose6;
        pose6.position.x = 0.032492179697122675;
        pose6.position.y = -0.0814728216582047;
        pose6.position.z = 0.08401846064911692;
        pose6.orientation.x = 0.06864384957945104;
        pose6.orientation.y = 0.27555892205004473;
        pose6.orientation.z = -0.23195179933670168;
        pose6.orientation.w = 0.9303513665158974;
        waypoints.push_back(pose6);

        // 目标点7 -28/-70/135/-36/0
        geometry_msgs::msg::Pose pose7;
        pose7.position.x = 0.0446287643769399;
        pose7.position.y = -0.08791412462470531;
        pose7.position.z = 0.08061218194929645;
        pose7.orientation.x = 0.06051325339911822;
        pose7.orientation.y = 0.242909963020376;
        pose7.orientation.z = -0.23418814928531106;
        pose7.orientation.w = 0.9394087538248804;
        waypoints.push_back(pose7);

        // 目标点8 -28/-70/141/-50/0
        geometry_msgs::msg::Pose pose8;
        pose8.position.x = 0.08054424192783191;
        pose8.position.y = -0.10699752705986922;
        pose8.position.z = 0.10661899188484153;
        pose8.orientation.x = 0.03779276087929698;
        pose8.orientation.y = 0.15177439309731033;
        pose8.orientation.z = -0.2389260449080508;
        pose8.orientation.w = 0.9583582763714517;
        waypoints.push_back(pose8);

        // 目标点9 -28/-72/150/-78/0 举平
        geometry_msgs::msg::Pose pose9;
        pose9.position.x = 0.09049845893474838;
        pose9.position.y = -0.11230423464398587;
        pose9.position.z = 0.1506514470154047;
        pose9.orientation.x = 0.006333520542832988;
        pose9.orientation.y = 0.025396788065378907;
        pose9.orientation.z = -0.24180305139626612;
        pose9.orientation.w = 0.969972254246971;
        waypoints.push_back(pose9);

        // 目标点10 -14/-72/150/-78/0 举平移
        geometry_msgs::msg::Pose pose10;
        pose10.position.x = 0.1078137015424794;
        pose10.position.y = -0.057002013797603834;
        pose10.position.z = 0.15304097497404734;
        pose10.orientation.x = 7.721304036228014e-06;
        pose10.orientation.y = 4.7830876074295094e-05;
        pose10.orientation.z = -0.12190999444880327;
        pose10.orientation.w = 0.9925411582932376;
        waypoints.push_back(pose10);

        // 目标点11 middle
        geometry_msgs::msg::Pose pose11;
        pose11.position.x = 0.11075168589927481;
        pose11.position.y = -1.091277667118024e-05;
        pose11.position.z = 0.2875988062936282;
        pose11.orientation.x = 1.8382147442206865e-06;
        pose11.orientation.y = 8.132110012412454e-05;
        pose11.orientation.z = -2.4453694472133078e-05;
        pose11.orientation.w = 0.9999999963927584;
        waypoints.push_back(pose11);
        /* #endregion */

        move_group_->stop();
        move_group_->setStartStateToCurrentState();
        moveit::planning_interface::MoveGroupInterface::Plan cartesian_plan;
        double fraction = move_group_->computeCartesianPath(waypoints, 0.01, 0.0, cartesian_plan.trajectory_);
        
        if (fraction < 0.9) {
            RCLCPP_ERROR(get_logger(), "初始路径规划失败，完成度: %f", fraction);
            return;
        }

        RCLCPP_INFO(get_logger(), "初始路径规划成功，开始执行...");
        move_group_->asyncExecute(cartesian_plan);
        bool is_stopped = false;
        bool is_forced = false;
        std::atomic<bool> motion_complete(false);
        auto start_time = std::chrono::steady_clock::now();
        const std::chrono::seconds timeout(15); // 设置15秒超时

        while (rclcpp::ok() && !motion_complete && !is_forced) {
            auto elapsed_time = std::chrono::steady_clock::now() - start_time;
            if (elapsed_time > timeout) {
                RCLCPP_ERROR(get_logger(), "运动执行超时");
                motion_complete = true;
                break;
    }
            if (!force_sign.load()) {
                if (!is_stopped) {
                    RCLCPP_INFO(get_logger(), "检测到过大力，尝试停止运动...");
                    move_group_->stop();
                    is_stopped = true;
                    is_forced = true;
                    RCLCPP_INFO(get_logger(), "运动已停止");
                }
            } else {
                if (is_stopped) {
                    RCLCPP_INFO(get_logger(), "力信号恢复，尝试继续运动...");
                    if (continueCartesianPath(waypoints)) {
                        RCLCPP_INFO(get_logger(), "已恢复运动");
                        is_stopped = false;
                    } else {
                        RCLCPP_INFO(get_logger(), "无法继续运动或路径已完成");
                        motion_complete = true;
                        break;
                    }
                }
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
        }

        if (motion_complete.load()) {
            RCLCPP_INFO(get_logger(), "运动执行循环结束（可能已完成或无法继续）");
        } else if (!rclcpp::ok()) {
            RCLCPP_INFO(get_logger(), "运动执行循环因 rclcpp 关闭而结束");
        }
        move_group_->stop();
        RCLCPP_INFO(get_logger(), "executeCartesianPath3 结束");
    }
};

int main(int argc, char** argv) {
    rclcpp::init(argc, argv);
    auto node = std::make_shared<CombinedNode>();

    rclcpp::executors::MultiThreadedExecutor executor;
    executor.add_node(node);

    RCLCPP_INFO(node->get_logger(), "节点已初始化，等待 result2_topic 消息...");
    RCLCPP_INFO(node->get_logger(), "开始执行器 spin");
    executor.spin();

    RCLCPP_INFO(node->get_logger(), "执行器 spin 结束");
    rclcpp::shutdown();
    return 0;
}